/*
 * @lc app=leetcode id=54 lang=cpp
 *
 * [54] Spiral Matrix
 */
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {

        vector<int> ret;
        if (matrix.size() < 1) {
            return ret;
        }

        int row = matrix.size();
        int col = matrix[0].size();

        int i = 0;
        int x, y;
        while(i < row/2 && i < col/2) {
            x = i;
            y = i;

            while(y < col-i-1) {
                ret.push_back(matrix[x][y]);
                y++;
            }
            while(x < row-i-1) {
                ret.push_back(matrix[x][y]);
                x++;
            }
            while(y > i) {
                ret.push_back(matrix[x][y]);
                y--;
            }
            while(x > i) {
                ret.push_back(matrix[x][y]);
                x--;
            }
            i++;
        }

        x = i;
        y = i;
        if ((row & 0x01 ) && x == row-i-1) {
            while(y < col-i) {
                ret.push_back(matrix[x][y]);
                y++;
            }
        } else if ((col & 0x01 ) && y == col-i-1) {
            while(x < row-i) {
                ret.push_back(matrix[x][y]);
                x++;
            }
        }
        return ret;
        
    }
};

